<template>
  <div v-if="order" class="order-detail">
    <!-- 宠物信息区块 -->
    <el-card class="detail-section">
      <template #header>
        <div class="section-header">
          <h3>宠物信息</h3>
        </div>
      </template>
      <div class="pet-info">
        <el-avatar :src="order.pet.avatar" :size="80" />
        <div class="pet-details">
          <h4>{{ order.pet.name }}</h4>
          <p>品种：{{ order.pet.breed }}</p>
          <p>年龄：{{ order.pet.age }}</p>
        </div>
      </div>
      <div v-if="order.pet.specialNotes" class="special-notes">
        <el-alert
          title="特殊注意事项"
          type="warning"
          :description="order.pet.specialNotes"
          show-icon
        />
      </div>
    </el-card>

    <!-- 服务详情区块 -->
    <el-card class="detail-section">
      <template #header>
        <div class="section-header">
          <h3>服务详情</h3>
        </div>
      </template>
      <div class="service-info">
        <h4>{{ order.service.name }}</h4>
        <p class="service-time">
          <el-icon><Timer /></el-icon>
          服务时长：{{ order.service.duration }}
        </p>
        <p class="appointment-time">
          <el-icon><Calendar /></el-icon>
          预约时间：{{ order.service.appointmentTime }}
        </p>
        <div class="service-items">
          <h5>服务项目</h5>
          <el-tag
            v-for="item in order.service.items"
            :key="item"
            class="service-item"
          >
            {{ item }}
          </el-tag>
        </div>
      </div>
    </el-card>

    <!-- 服务进度区块 -->
    <el-card class="detail-section">
      <template #header>
        <div class="section-header">
          <h3>服务进度</h3>
        </div>
      </template>
      <OrderProgress :progress="order.progress" />
    </el-card>

    <!-- 订单操作区块 -->
    <div class="order-actions">
      <template v-if="order.status === 'unpaid'">
        <el-button type="primary" @click="handlePayment">立即支付</el-button>
      </template>
      <template v-if="order.canCancel">
        <el-button type="danger" @click="handleCancel">取消订单</el-button>
      </template>
      <template v-if="order.canModify">
        <el-button @click="handleModifyTime">修改时间</el-button>
      </template>
      <el-button @click="handleContactService">联系商家</el-button>
      <el-button @click="handleReorder">再次预约</el-button>
      <template v-if="order.status === 'completed'">
        <el-button type="primary" @click="handleRateService">评价服务</el-button>
      </template>
    </div>
  </div>
  <div v-else class="loading-state">
    <el-empty description="加载中..." />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import OrderProgress from '../components/OrderProgress.vue';

const route = useRoute();
const router = useRouter();
const orderId = route.params.id;
const order = ref(null);

// 模拟订单数据
const mockOrders = {
  'ORD2024001': {
    id: 'ORD2024001',
    date: '2024-03-15',
    pet: {
      name: '球球',
      avatar: '/assets/pet-avatar.png',
      breed: '金毛寻回犬',
      age: '2岁',
      specialNotes: '对某些洗护用品过敏，需要使用特定品牌'
    },
    service: {
      type: 'grooming',
      name: '精致美容套餐',
      duration: '120分钟',
      items: [
        '专业洗澡',
        '造型修剪',
        '指甲修剪',
        '耳道清洁',
        '香波护理'
      ],
      appointmentTime: '2024-03-20 14:30'
    },
    progress: [
      { time: '2024-03-15 10:30', status: 'booked', title: '预约成功' },
      { time: '2024-03-20 14:30', status: 'pending', title: '等待服务' }
    ],
    amount: 299,
    status: 'pending',
    canCancel: true,
    canModify: true
  },
  'ORD2024002': {
    id: 'ORD2024002',
    date: '2024-03-14',
    pet: {
      name: '奥利奥',
      avatar: '/assets/pet-avatar.png',
      breed: '边境牧羊犬',
      age: '1岁',
      specialNotes: '性格活泼，需要特别关注'
    },
    service: {
      type: 'medical',
      name: '年度体检套餐',
      duration: '90分钟',
      items: [
        '常规体检',
        '血液检查',
        '疫苗接种',
        '驱虫服务'
      ],
      appointmentTime: '2024-03-18 10:00'
    },
    progress: [
      { time: '2024-03-14 15:20', status: 'booked', title: '预约成功' }
    ],
    amount: 599,
    status: 'unpaid',
    canCancel: true,
    canModify: true
  },
  'ORD2024003': {
    id: 'ORD2024003',
    date: '2024-03-13',
    pet: {
      name: '小白',
      avatar: '/assets/pet-avatar.png',
      breed: '柴犬',
      age: '8个月',
      specialNotes: '第一次参加训练课程'
    },
    service: {
      type: 'training',
      name: '基础训练课程',
      duration: '60分钟',
      items: [
        '基础指令训练',
        '社交礼仪',
        '行为矫正',
        '互动游戏'
      ],
      appointmentTime: '2024-03-16 15:00'
    },
    progress: [
      { time: '2024-03-13 09:00', status: 'booked', title: '预约成功' },
      { time: '2024-03-16 15:00', status: 'inProgress', title: '训练进行中' }
    ],
    amount: 799,
    status: 'inProgress',
    canCancel: false,
    canModify: false
  },
  'ORD2024004': {
    id: 'ORD2024004',
    date: '2024-03-12',
    pet: {
      name: '可可',
      avatar: '/assets/pet-avatar.png',
      breed: '泰迪犬',
      age: '3岁',
      specialNotes: '需要定期服用心脏病药物'
    },
    service: {
      type: 'boarding',
      name: '豪华寄养7天',
      duration: '7天',
      items: [
        '独立房间',
        '定时喂食',
        '日常运动',
        '洗护服务',
        '24小时监控'
      ],
      appointmentTime: '2024-03-15 09:00'
    },
    progress: [
      { time: '2024-03-12 14:00', status: 'booked', title: '预约成功' },
      { time: '2024-03-15 09:00', status: 'inProgress', title: '开始寄养' },
      { time: '2024-03-22 09:00', status: 'completed', title: '服务完成' }
    ],
    amount: 1299,
    status: 'completed',
    canCancel: false,
    canModify: false
  }
};

// 模拟获取订单详情
const fetchOrderDetail = async () => {
  const mockOrder = mockOrders[orderId];
  if (mockOrder) {
    order.value = mockOrder;
  } else {
    ElMessage.error('订单不存在');
    router.push('/orders');
  }
};

const handlePayment = async () => {
  try {
    await ElMessageBox.confirm('确认支付订单？', '支付确认');
    // 模拟支付成功
    ElMessage.success('支付成功');
    order.value.status = 'pending';
    order.value.progress.push({
      time: new Date().toLocaleString(),
      status: 'pending',
      title: '支付完成'
    });
  } catch {
    // 用户取消支付
  }
};

const handleCancel = async () => {
  try {
    await ElMessageBox.confirm(
      '取消订单后，需要重新预约才能享受服务，是否确认取消？',
      '取消订单',
      {
        type: 'warning'
      }
    );
    // 模拟取消订单
    order.value.status = 'cancelled';
    order.value.canCancel = false;
    order.value.canModify = false;
    order.value.progress.push({
      time: new Date().toLocaleString(),
      status: 'cancelled',
      title: '订单已取消'
    });
    ElMessage.success('订单已取消');
  } catch {
    // 用户取消操作
  }
};

const handleModifyTime = () => {
  ElMessageBox.prompt('请选择新的预约时间', '修改预约时间', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPattern: /^202[4-9]-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]) ([01]\d|2[0-3]):[0-5]\d$/,
    inputErrorMessage: '请输入正确的时间格式：YYYY-MM-DD HH:mm'
  }).then(({ value }) => {
    order.value.service.appointmentTime = value;
    order.value.progress.push({
      time: new Date().toLocaleString(),
      status: 'pending',
      title: '修改预约时间'
    });
    ElMessage.success('预约时间修改成功');
  }).catch(() => {
    // 用户取消操作
  });
};

const handleContactService = () => {
  ElMessage.info('正在连接客服，请稍候...');
};

const handleReorder = () => {
  router.push({
    path: '/reservation',
    query: {
      serviceType: order.value.service.type,
      petId: order.value.pet.id
    }
  });
};

const handleRateService = () => {
  ElMessageBox.prompt('请对本次服务进行评价（1-5星）', '服务评价', {
    confirmButtonText: '提交评价',
    cancelButtonText: '取消',
    inputPattern: /^[1-5]$/,
    inputErrorMessage: '请输入1-5的数字'
  }).then(({ value }) => {
    ElMessage.success(`评价成功，感谢您的${value}星评价！`);
    order.value.progress.push({
      time: new Date().toLocaleString(),
      status: 'completed',
      title: '服务评价完成'
    });
  }).catch(() => {
    // 用户取消操作
  });
};

onMounted(() => {
  fetchOrderDetail();
});
</script>

<style scoped>
.order-detail {
  padding: 30px;
  max-width: 800px;
  margin: 0 auto;
}

.detail-section {
  margin-bottom: 24px;
  transition: all 0.3s ease;
}

.detail-section:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.08);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.section-header h3 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #333;
}

.pet-info {
  display: flex;
  gap: 24px;
  margin-bottom: 24px;
  align-items: center;
}

.pet-details h4 {
  margin: 0 0 8px;
  font-size: 18px;
  font-weight: 600;
}

.pet-details p {
  margin: 6px 0;
  color: #606266;
  font-size: 15px;
}

.special-notes {
  margin-top: 20px;
}

.service-info h4 {
  margin: 0 0 16px;
  font-size: 18px;
  font-weight: 600;
}

.service-time,
.appointment-time {
  display: flex;
  align-items: center;
  gap: 10px;
  margin: 10px 0;
  color: #606266;
  font-size: 15px;
}

.service-items {
  margin-top: 20px;
}

.service-items h5 {
  margin: 0 0 12px;
  font-size: 16px;
  font-weight: 500;
}

.service-item {
  margin: 0 10px 10px 0;
  transition: all 0.3s ease;
}

.service-item:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.order-actions {
  display: flex;
  gap: 16px;
  justify-content: center;
  margin-top: 40px;
  flex-wrap: wrap;
}

:deep(.el-button) {
  padding: 12px 24px;
  font-size: 16px;
  border-radius: 8px;
  transition: all 0.3s ease;
}

:deep(.el-button--primary) {
  background-color: #e76f51;
  border-color: #e76f51;
}

:deep(.el-button--primary:hover) {
  background-color: #d65c41;
  border-color: #d65c41;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(231, 111, 81, 0.2);
}

:deep(.el-button--danger) {
  background-color: #f56c6c;
  border-color: #f56c6c;
}

:deep(.el-button--danger:hover) {
  background-color: #f78989;
  border-color: #f78989;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(245, 108, 108, 0.2);
}

.loading-state {
  padding: 60px;
  text-align: center;
}
</style>